package main.java.com.gdkj.dto.socket;

import cn.hutool.core.util.ByteUtil;
import lombok.Data;
import main.java.com.gdkj.util.ByteUtils;

import java.io.Serializable;
import java.nio.ByteOrder;

/**
 * 业务解析数据对象
 */
@Data
public class BussDataPacket implements Serializable {
    private byte[] dataLength;      // 数据长度  4个字节
    private byte[] commandData;   // 指令数据

    public BussDataPacket(){

    }

    /**
    * 构造参数
    **/
    public BussDataPacket(byte[] dataLength, byte[] commandData) {
        this.dataLength = dataLength;
        this.commandData = commandData;
    }

    public BussDataPacket(String commandDataJson) {
        this.dataLength = ByteUtils.intToBytes2(commandDataJson.length());
        this.commandData = commandDataJson.getBytes();
    }

    public BussDataPacket(int length, String data) {
        this.dataLength = ByteUtils.intToBytes2(length);
        this.commandData = data.getBytes();
    }

    /**
    * 转换成byte
    **/
    public byte[] toByteArray() {
        int dataLength = commandData.length;
        byte[] result = new byte[dataLength+4];
        byte[] lengthType = ByteUtil.intToBytes(dataLength,ByteOrder.BIG_ENDIAN);
        System.arraycopy(lengthType, 0, result, 0, 4);
        System.arraycopy(commandData, 0, result, 4, commandData.length);
        return result;
    }
}